package com.wzy.shirostudy.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @program: shiro-study
 * @description: 测试shiro类
 * @author: 1
 * @create: 2020-04-15 13:44
 **/
@Slf4j
public class Tutorial {
    public static void main(String[] args) {
        log.info("My First Apache Shiro Application");

        //1.
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        //2.
        SecurityManager securityManager = factory.getInstance();

        //3.
        SecurityUtils.setSecurityManager(securityManager);

        Subject currentUser = SecurityUtils.getSubject();

        if ( !currentUser.isAuthenticated() ) {
            //collect user principals and credentials in a gui specific manner
            //such as username/password html form, X509 certificate, OpenID, etc.
            //We'll use the username/password example here since it is the most common.
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            try {
                currentUser.login( token );
                //if no exception, that's it, we're done!
            } catch ( UnknownAccountException uae ) {
                //username wasn't in the system, show them an error message?
            } catch ( IncorrectCredentialsException ice ) {
                //password didn't match, try again?
            } catch ( LockedAccountException lae ) {
                //account for that username is locked - can't login.  Show them a message?
            } catch ( AuthenticationException ae ) {

            }
            //unexpected condition - error?
        }

        log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
        //判断是否拥有该角色(schwartz/施瓦茨)
        if ( currentUser.hasRole( "schwartz" ) ) {
            log.info("愿施瓦茨和你在一起！" );
        } else {
            log.info( "你好，只是凡人." );
        }

        //判断是否拥有该权限 lightsaber:wield
        if ( currentUser.isPermitted( "lightsaber:wield" ) ) {
            log.info("您可以使用光剑环。明智地使用它.");
        } else {
            log.info("抱歉，光剑戒指仅适用于Schwartz大师.");
        }

        if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
            log.info("您可以使用牌照（id) eagle5 来驾驶winnebago这是关键 ,玩得开心！");
        } else {
            log.info("抱歉，您不允许驾驶“ eagle5” winnebago!");
        }



        //登出 删除所有识别信息，并使它们的会话也无效。
        currentUser.logout();
        System.exit(0);
    }
}
